<template>
  <div class="app-container">
    <el-row class="header-nav">
      <el-col class="header-nav-left"
              :span="12">
        <img src="static/img/newLogo.png" />
        <!-- <div class="newLogo"></div> -->
      </el-col>
      <el-col class="header-nav-right"
              :span="12">
        <span>{{title}}</span>
      </el-col>
    </el-row> 　
    <el-row class="main-section">
      <div class="main-box">
        <div style="font-size:16px; color: #fff; font-weight: bold;">
          <span class="tips">
            {{custom.tips}}
          </span>
        </div>
        <br>
        <el-form ref="form"
                 class="elForm"
                 :model="form"
                 label-width="120px">
          <el-row :gutter="30">
            <!-- 身份证信息 -->
            <el-col :span="10">
              <el-form-item label="PCC卡号"
                            label-width="80px">
                <el-input v-model="form.tcCode"
                          disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <!-- 运通卡信息 -->
              <el-form-item label="车牌"
                            label-width="80px"
                            class="labelRed">
                <span style="width: 80px; float: left;">
                  <el-select v-model="form.vehicleColor"
                             placeholder="">
                    <el-option v-for="item in vehicleColor"
                               :key="item.id"
                               :label="item.value"
                               :value="item.id">
                    </el-option>
                  </el-select>
                </span>
                <span style="width: 80px; float: left; margin-left: 10px;">
                  <el-input v-model="form.vehiclePy"></el-input>
                </span>
                <span style="width: 120px; float: left; margin-left: 10px;">
                  <el-input @blur="changeVehicleKey"
                            v-model="form.vehicleKey"></el-input>
                </span>
                <span style="width: 80px; float: left;; margin-left: 10px;">
                  <el-select v-model="form.vehicleSuf"
                             placeholder="">
                    <el-option v-for="item in vehicleSuf"
                               :key="item.value"
                               :label="item.value"
                               :value="item.value">
                    </el-option>
                  </el-select>
                </span>
              </el-form-item>

            </el-col>
          </el-row>

          <el-row :gutter="30">
            <!-- 公司名称 -->
            <el-col :span="24">
              <el-form-item label="公司名称"
                            label-width="80px">
                <el-input v-model="form.companyName"
                          disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="0">
            <!-- 司机姓名 -->
            <el-col :span="6">
              <el-form-item label="司机姓名"
                            label-width="80px"
                            class="labelRed">
                <el-input v-model="form.idName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <!-- 运通卡信息 -->
              <el-form-item label="司机联系方式">
                <el-input v-model="form.manTel"
                          v-bind:class="{ labelRed: custom.manTelRequire }"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <!-- 运通卡信息 -->
              <el-form-item label="身份证号码"
                            class="labelRed">
                <el-input v-model="form.driverCardId"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="0">
            <!-- 身份证信息 -->
            <el-col :span="14">
              <el-form-item label="原因"
                            label-width="80px">
                <!-- <el-input v-model="form.reason" disabled></el-input> -->
                <el-select v-model="form.reason"
                           style="width: 100%">
                  <el-option v-for="item in reasons"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="10">
              <!-- 运通卡信息 -->
              <el-form-item label="SSD回执号"
                            v-if="custom.showReturnReceiptId"
                            class="labelRed">
                <el-input v-model="form.returnReceiptId"
                          disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="30">
            <!-- 身份证信息 -->
            <el-col :span="10">
              <el-form-item label="设备类型"
                            label-width="80px">
                <el-select v-model="form.idDevice"
                           disabled>
                  <el-option v-for="item in idDevices"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <!-- 运通卡信息 -->
              <el-form-item label="操作方式">
                <el-select style="width: 100%"
                           v-model="form.operatingMode"
                           disabled>
                  <el-option v-for="item in operats"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div style="text-align: center; margin-top: 25px;"
           class="btgs">
        <el-button :disabled="custom.pccButtonDisable"
                   @click="readCard('ic')"
                   class="blue-btn">
          <div>
            <img src="static/img/ICON-1.png"
                 alt="">
            <span class="bt-label">刷PCC卡</span>
          </div>
        </el-button>
        <el-button @click="readCard('id')"
                   class="blue-btn">
          <div>
            <img src="static/img/ICON-2.png"
                 alt="">
            <span class="bt-label">刷身份证</span>
          </div>
        </el-button>
        <el-button :disabled="custom.resetButtonDisable"
                   @click="reset"
                   class="blue-btn">
          <div>
            <img src="static/img/ICON-3.png"
                 alt="">
            <span class="bt-label">重置</span>
          </div>
        </el-button>
        <el-button @click="insertIDTractor"
                   class="blue-btn">
          <div>
            <img src="static/img/ICON-4.png"
                 alt="">
            <span class="bt-label">确定</span>
          </div>
        </el-button>
        <el-button @click="logout"
                   class="warning-btn">
          <div>
            <img src="static/img/ICON-5.png"
                 alt="">
            <span class="bt-label">取消</span>
          </div>
        </el-button>

        <!-- <el-button>取消</el-button> -->
      </div>
    </el-row>
    <return-receipts ref="recepitsDialog"
                     @updateTractor="updateTractor"></return-receipts>
  </div>
</template>

<script>

import { GSAConstants } from '@/utils/access'
import ReturnReceipts from './return_receipts'
import { isBlank, checkCardId } from '@/utils/validate'
import {
  showWarningMsg,
  showErrorMsg,
  log
} from '@/utils/message'
export default {
  components: { ReturnReceipts },
  props: {
    title: {
      type: String,
      default: function () {
        return ''
      }
    },
    custom: {
      type: Object,
      default: function () {
        return {}
      }
    }
    , ic: {
      type: String,
      default: function () {
        return ''
      }
    },
    url: {
      type: String,
      default: function () {
        return ''
      }
    },
    reasons: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data () {
    return {
      msgInter: null,
      idThread: null,
      icThread: null,
      hasPccCard: false,
      showMessage: {
        msg: '请刷卡......',
        type: 'success',
      },
      vehicleColor: [
        { id: '蓝', value: '蓝' },
        { id: '黑', value: '黑' },
        { id: '绿', value: '绿' },
        { id: '红', value: '红' },
        { id: '黄', value: '黄' },
        { id: '白', value: '白' }
      ],
      idDevices: [{
        value: '1',
        label: '一二代一体机'
      }, {
        value: '2',
        label: '二代证读卡器'
      }],
      vehicleSuf: [{
        value: '',
        label: ''
      }, {
        value: '港',
        label: '港'
      }, {
        value: '澳',
        label: '澳'
      }],
      operats: [{
        value: '1',
        label: '二代身份证读卡'
      }, {
        value: '2',
        label: '一代身份证扫描'
      }, {
        value: '3',
        label: '二代身份证扫描'
      }],
      vehicleKeyOut: null,
      form: {
        tcCode: '',
        skipCheck: '',
        pccId: '',
        companyName: '',
        returnReceiptId: '',
        //  "无PCC卡", "PCC卡已坏", "无效身份证", "使用第一代身份证", "使用港澳身份证",
        // "使用驾驶证", "使用从业资格证", "无任何证件", "其他" 
        reason: '',
        idDevice: '1',
        operatingMode: '1',
        idName: '',
        manTel: '',
        driverCardId: '',
        // "蓝", "黑", "绿", "红", "黄", "白"
        vehicleColor: '黄',
        vehiclePy: '',
        vehicleKey: '',
        // "", "港", "澳" 
        vehicleSuf: ''
      }
    }
  },
  created () {

  },
  mounted () {
  },
  methods: {
    //  osd 更新车辆的方法
    updateTractor (notice) {
      this.form.vehicleColor = notice.tidNgenColor
      this.form.vehiclePy = notice.tidNgenPy
      this.form.vehicleKey = notice.tidNgenKey
      this.form.returnReceiptId = notice.idNoticeId
      this.form.companyName = notice.fullName

      if (!isBlank(notice.idName)) {
        this.form.tcCode = notice.tcCode
        this.form.permitNo = notice.tcCode
        this.form.driverCardId = notice.idNumber
        this.form.idName = notice.idName
        this.form.manTel = notice.manTel
      }
    },
    // 变更车牌号的方法 SSD
    changeVehicleKeySSD () {
      if (isBlank(this.form.vehiclePy)) {
        showWarningMsg("请输入车牌省份")
        return false
      }

      if (isBlank(this.form.vehicleKey)) {
        showWarningMsg("请输入车牌号码")
        return false
      }

      // 防抖
      setTimeout(() => {
        const qd = {
          tidNgenColor: this.form.vehicleColor,
          tidNgenPy: this.form.vehiclePy,
          tidNgenKey: this.form.vehicleKey
        }

        let message = {
          dt: qd,
          ic: GSAConstants().TOPIC_FIND_TRACTOR_BY_VEHICLE.ic,
          en: false
        }
        const url = GSAConstants().TOPIC_FIND_TRACTOR_BY_VEHICLE.url
        log('执行代码 this.$emit(customSentMqttMsg, this.$props.url, message)', url, message)
        this.$emit('customSentMqttMsg', url, message)
      }, 1500)
    },
    // 变更车牌号的方法 OSD
    changeVehicleKeyOSD () {
      // 自动根据车牌号 查询回执列表， 然后弹出dialog， 让用户选择后回写数据
      if (isBlank(this.form.vehicleKey)) {
        return
      }

      const shortKeyValue = this.form.vehicleKey
      this.form.vehicleKey = ''
      this.form.vehiclePy = ''
      this.form.vehicleColor = '黄'
      this.form.tcCode = ''
      this.form.permitNo = ''
      this.form.companyName = ''

      const qd = {
        shortKey: shortKeyValue
      }
      let message = {
        dt: qd,
        ic: GSAConstants().TOPIC_QUERY_RETURN_RECEIPTS.ic,
        en: false
      }
      const url = GSAConstants().TOPIC_QUERY_RETURN_RECEIPTS.url
      log('执行代码 this.$emit(customSentMqttMsg, this.$props.url, message)', url, message)
      this.$emit('customSentMqttMsg', url, message)
    },
    // 变更车牌号的方法 
    changeVehicleKey () {
      // ssd 跟 osd逻辑不一样， 这里区分开来处理
      if (GSAConstants().TOPIC_MANUAL_SSD.ic === this.$props.ic) {
        this.changeVehicleKeySSD()
      } else if (GSAConstants().TOPIC_MANUAL_OSD.ic === this.$props.ic) {
        this.changeVehicleKeyOSD()
      }
    },
    // mqtt 消息回掉
    handleSuccessMqttMessage (messageObject) {
      log('接收到系统返回数据， 准备渲染数据', JSON.stringify(messageObject))
      if (messageObject.ic === GSAConstants().TOPIC_FIND_TRACTOR_BY_VEHICLE.ic) {
        let dt = messageObject.dt
        if (dt) {
          this.form.tcCode = dt.code
          this.form.permitNo = dt.code
          if (!isBlank(dt.companyName)) {
            this.form.companyName = dt.companyName
          }
          this.setParentForm(this.form)
        }
      } else if (GSAConstants().TOPIC_QUERY_RETURN_RECEIPTS.ic === messageObject.ic) {
        if (!messageObject.dt || messageObject.dt.length === 0) {
          showErrorMsg('无卡车辆，请联系SSD登记审核！')
          return
        }
        this.$refs.recepitsDialog.show(messageObject.dt)

      }
    },
    setParentForm (form) {
      this.$emit('setForm', form)
    },
    // 读ID成功
    readIcCardSuccess () {
      log('读PCC卡成功， 关闭读卡线程')
      if (this.icThread) {
        clearInterval(this.icThread)
      }
      this.hasPccCard = true
    },
    // 读ID成功
    readIdCardSuccess () {
      log('读ID卡成功， 关闭读卡线程')
      if (this.idThread) {
        clearInterval(this.idThread)
      }
    },
    // 开启读卡
    readCard (type) {
      let count = 1;
      const readCardInterval = setInterval(() => {
        log('开始尝试读卡', type, '尝试次数', count)
        this.$emit('readCard', type)
        count++

        if (count > 3) {
          log('关闭读卡，', type, '尝试次数', count)
          if (type === 'ic') {
            showErrorMsg('PCC卡读取失败，请重新刷卡')
          } else {
            showErrorMsg('身份证读取失败，请重新刷身份证')
          }
          clearInterval(readCardInterval)
        }
      }, 1000)


      // 防止用户多次频繁点击读卡的逻辑， 关闭上一次读卡线程
      if (type === 'ic') {
        // 关闭之前的读卡线程， 因为重新开了一个
        if (this.icThread) {
          clearInterval(this.icThread)
        }
        this.icThread = readCardInterval
      } else {
        // 关闭之前的读卡线程， 因为重新开了一个
        if (this.idThread) {
          clearInterval(this.idThread)
        }
        this.idThread = readCardInterval
      }
    },
    showMsg (dt) {
      this.showMessage.msg = dt.msg
      this.showMessage.type = dt.type
      let type = ''
      if (dt.type === 'error') {
        type = 'error'
      } else if (dt.type === 'green') {
        type = 'success'
      } else {
        type = 'info'
      }

      if (this.msgInter) {
        clearTimeout(this.msgInter)
      }
      this.msgInter = setTimeout(() => {
        this.$message({
          message: dt.msg,
          type: type
        })
      }, 1000)
    },
    setForm (form) {
      if (form.hasPcc) {
        this.hasPccCard = true
      }

      // permitNo 才是pcc卡号
      form.tcCode = form.permitNo
      this.form = { ...this.form, ...form }
    },
    // 跳过一年三次校验
    skipCheck () {
      this.form.skipCheck = true
      this.insertIDTractor()
    },
    insertIDTractor () {
      log('insertIDTractor')
      // 校验参数
      if (!this.validateForm()) {

        return false;
      }

      const qd = {
        idCard: this.form.driverCardId,
        manTel: this.form.manTel,
        skipCheckIdNoticeYear: this.form.skipCheck,
        transid: this.form.transid,
        idName: this.form.idName,
        tidNgenColor: this.form.vehicleColor,
        tidNgenPy: this.form.vehiclePy,
        tidNgenKey: this.form.vehicleKey,
        tidNgenSuf: this.form.vehicleSuf,
        tcCode: this.form.tcCode,
        companyName: this.form.companyName,
        reason: this.form.reason,
        returnReceiptId: this.form.returnReceiptId
      }


      let message = {
        dt: qd,
        ic: this.$props.ic,
        en: false
      }
      log('执行代码 this.$emit(customSentMqttMsg, this.$props.url, message)', this.$props.url, message)
      this.$emit('customSentMqttMsg', this.$props.url, message)

      // 恢复false
      this.form.skipCheck = false
    },
    // 校验表单是否可以提交
    validateForm () {
      if (isBlank(this.form.vehiclePy)) {
        showWarningMsg("请输入车牌省份")
        return false
      }

      if (isBlank(this.form.vehicleKey)) {
        showWarningMsg("请输入车牌号码")
        return false
      }

      const driveName = this.form.idName
      if (isBlank(driveName) || driveName.length < 2 || driveName.length > 6) {
        showWarningMsg("司机姓名应该在2-6个字")
        return false
      }

      // 不能有数字
      let reg = /\d/
      if (reg.test(driveName)) {
        showWarningMsg("司机姓名不能有数字")
        return false
      }

      // 司机身份证号
      const driverCardId = this.form.driverCardId
      if (isBlank(driverCardId)) {
        showWarningMsg("请输入有效的身份证号")
        return false
      }

      if (driverCardId.length === 18) {
        if (!checkCardId(driverCardId)) {
          showWarningMsg("请输入有效的身份证号")
          return false
        }
      } else if (driverCardId.length !== 15) {
        showWarningMsg("请输入有效的身份证号")
        return false
      } else {
        if (!/^\d+$/.test(driverCardId)) {
          //15位的必须全部是数字
          showWarningMsg("请输入有效的身份证号")
          return false
        }
      }

      // check returnReceiptId
      if (!this.hasPccCard && isBlank(this.form.returnReceiptId)) {
        showWarningMsg("请输入回执编号")
        return false
      }

      if (isBlank(this.form.reason)) {
        showWarningMsg("原因为必输项")
        return false
      } else if (isBlank(this.form.returnReceiptId) && "无效身份证" === this.form.reason) {
        // TODO 需要后端在接口中校验reason， 校验放在submit请求里
      }
      // driverNameField 
      return true
    },
    // reset
    reset () {
      this.form = {
        tcCode: '',
        pccId: '',
        companyName: '',
        returnReceiptId: '',
        //  "无PCC卡", "PCC卡已坏", "无效身份证", "使用第一代身份证", "使用港澳身份证",
        // "使用驾驶证", "使用从业资格证", "无任何证件", "其他" 
        reason: '',
        idDevice: '1',
        operatingMode: '1',
        idName: '',
        manTel: '',
        driverCardId: '',
        // "蓝", "黑", "绿", "红", "黄", "白"
        vehicleColor: '黄',
        vehiclePy: '',
        vehicleKey: '',
        // "", "港", "澳" 
        vehicleSuf: ''
      }
      this.hasPccCard = false
      this.$emit('setForm', this.form)
    },
    logout () {
      this.$emit('logout')
    }
  },
}
</script>

<style scoped>
.line {
  text-align: center;
}

.header-nav {
  width: 100%;
  height: 45px;
  padding: 0 15px;
  background: linear-gradient(180deg, #f7fbff 0%, #ebf0ff 100%);
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.5), inset 0px -1px 2px 0px #b0b9ce;
}
.header-nav > .header-nav-left {
  cursor: pointer;
}
.header-nav > .header-nav-left > img {
  height: 35px;
  margin-top: 5px;
}
.header-nav > .header-nav-right {
  height: 100%;
  padding-top: 7.5px;
  /* display:flex; */
  text-align: right;
  align-items: center;
}
.header-nav > .header-nav-right > span {
  font-size: 17px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  color: #213767;
  line-height: 26px;
  text-shadow: 0px 1px 0px rgba(255, 255, 255, 0.5);
}

.main-section {
  width: 100%;
  background: url("/static/img/bg.png");
  height: calc(100vh - 45px);
  overflow: hidden;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  padding: 45px;
}

.left-box-center2 {
  margin: auto;
  margin-top: 20px;
  width: 400px;
}

.color-green {
  color: rgb(109, 238, 109);
}
.color-blue {
  color: blue;
}
.left-box-center2-mession {
  height: 100px;
  width: 300px;
  font-size: 21px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  color: #06ecc6;
  display: flex;
  float: right;
  line-height: 30px;
  align-items: center;
}
.left-box-center2 img {
  width: 80px;
  height: 80px;
}

.main-box {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 5px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 100%;
  padding: 18px;
}

.main-box >>> .el-input {
  font-size: 18px;
}

.app-container {
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-size: 12px;
  padding: 0px;
}

.vehicleColor {
  display: block;
  background-color: #dcdfe6;
  padding-top: 5px;
  width: 50px;
  height: 40px;
  opacity: 0.6;
  line-height: 30px;
  border-radius: 3px;
  margin-left: 10px;
  float: left;
  text-align: center;
}

.labelRed >>> .el-form-item__label {
  color: red;
}

.elForm {
  background: #fdfdfd;
  border-radius: 5px;
  padding: 25px;
}

.el-icon-my-swiping {
  background: url(/static/img/ICON-1.png);
  background-size: cover;
}

.elForm >>> .el-form-item__label {
  font-size: 14px;
  font-weight: bold;
}

.blue-btn {
  background-color: #e5f3ff;
}

.warning-btn {
  background-color: #ffbe9e;
}

.bt-label {
  display: block;
  float: right;
  margin-left: 5px;
  height: 40px;
  width: 50px;
  font-size: 15px;
  font-weight: bold;
  line-height: 50px;
}

.btgs img {
  width: 40px;
}

.btgs >>> button {
  padding: 12px 18px;
}
　 .btgs {
  font-size: 16px;
  line-height: 15px;
}
.el-icon-my-swiping:before {
  content: "替";
  font-size: 16px;
  visibility: hidden;
}
</style>
